package in.muton.edushare.newentities.upgraded.singleInvite;

import in.muton.edushare.auth.roles.UnivRoleCheck;
import in.muton.edushare.newentities.upgraded.InviteUtils;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.GroupsMembersDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Groups;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class GroupInvite implements SingleAudienceInvite {
	private static final long serialVersionUID = 393820343891417617L;
	private IModel<Groups> group;

	public GroupInvite(IModel<Groups> group) {
		this.group = group;
	}

	public List<String> inviteUsers(int role, CayenneList<Users> userList, ORMInterface ormInterface) {
		List<IModel<Users>> users = userList.getObject();
		List<String> fbd = new ArrayList<String>();
		Universities univ = group.getObject().getUniversity();
		for(IModel<Users> u:users){
			if(InviteUtils.isUnivSubscriber(univ, u.getObject())){
				if (u.getObject().isGroupMember(group.getObject())) {
					fbd.add(u.getObject().getCompleteUserName()+ "is already present in this group.");
				}else{
					new GroupsMembersDAO(ormInterface).addNewMember(group
						.getObject(), u.getObject(), role);
					fbd.add("Invitation is  sent to " + u.getObject().getCompleteUserName());
				}
			}else{
				fbd.add(u.getObject().getCompleteUserName()+ " cannot be added. Please make sure the user is a university member.");
			}
		}
		return fbd;
	}

	public List<String> inviteUsers(int role, List<CayenneList<Users>> userList, ORMInterface ormInterface) {
		List<String> strList = new ArrayList<String>();
		for (CayenneList<Users> u : userList) {
			strList.addAll(inviteUsers(role, u, ormInterface));
		}
		return strList;
	}

	public List<String> inviteUsers(int role, String[] userList, ORMInterface ormInterface) {
		List<String> feedback = new ArrayList<String>();
		for (String userId : userList) {
			Users u = InviteUtils.getUserByString(userId, ormInterface);
			UnivRoleCheck urc = new UnivRoleCheck(group.getObject()
					.getUniversity(), u);
			if (u != null && (urc.isMember() || urc.isInvited())) {
				feedback.add(inviteUsers(role, u, ormInterface));
			} else {
				feedback
						.add(userId
								+ " cannot be added. Please make sure the user is a university member.");
			}
		}

		return feedback;
	}
	
	public String inviteUsers(int role, Users u, ORMInterface orm){
		if (u.isGroupMember(group.getObject())) {
			return (u.getCompleteUserName() + "is already present in this group.");
		} else {
			new GroupsMembersDAO(orm).addNewMember(group
					.getObject(), u, role);
			return ("Invitation is  sent to " + u.getCompleteUserName());
		}
	}

}
